'use strict'

import React from 'react'
import _ from 'lodash'

const echarts = require('echarts')

/**
 * 虎符echarts
 * options option选项
 */
export default class HufuEcharts extends React.Component {
  constructor(props) {
    super(props)
    this.chartInstance = null
    this.options = _.merge({}, props.options || {})
  }

  componentDidMount() {
    this.initChart()
    window.addEventListener('resize', this.resize)
  }

  componentWillReceiveProps(nextProps) {
    this.resetOptions(nextProps.options)
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resize)
  }

  /**
   * 浏览器大小改变事件
   */
  resize = () => {
    this.chartInstance && this.chartInstance.resize()
  }

  /*
   * 当参数改变时重设图表组件
   */
  resetOptions(options) {
    this.chartInstance
      && this.chartInstance.setOption(_.merge({}, this.options, options))
    this.resize()
  }

  /**
   * 初始化图标
   */
  initChart() {
    this.chartInstance = echarts.init(this.chartDomRef)
    this.chartInstance.setOption(this.options)
  }

  render() {
    return (
      <div
        ref={(div) => {
          this.chartDomRef = div
        }}
        style={{ height: '100%', width: '100%' }}
      />
    )
  }
}
